import 'package:flutter/material.dart';
import 'package:flutter_base/src/config/app_colors.dart';
import 'package:flutter_base/src/config/color_util.dart';

/// 自定义底部弹出选择器
class CustomBottomPicker<T> extends StatefulWidget {
  /// 标题
  final String title;

  /// 选项数据 - 可以是字符串列表或Map列表
  final List<T> options;

  /// 显示键名（仅当T为Map<String, dynamic>时有效）
  final String? displayKey;

  /// 初始选中索引
  final int initialIndex;

  /// 确认回调 - 返回选中的索引和选中的项
  final void Function(int selectedIndex, T selectedItem) onConfirm;

  /// 取消回调
  final VoidCallback? onCancel;

  /// 主题色
  final Color? primaryColor;

  /// 选择器高度
  final double pickerHeight;

  /// 头部高度
  final double headerHeight;

  /// 选项高度
  final double itemHeight;

  const CustomBottomPicker({
    super.key,
    required this.title,
    required this.options,
    required this.onConfirm,
    this.displayKey,
    this.initialIndex = 0,
    this.onCancel,
    this.primaryColor,
    this.pickerHeight = 300,
    this.headerHeight = 50,
    this.itemHeight = 40,
  });

  /// 显示底部选择器
  static Future<T?> show<T>({
    required BuildContext context,
    required String title,
    required List<dynamic> options,
    required void Function(int selectedIndex, dynamic selectedItem) onConfirm,
    String? displayKey,
    int initialIndex = 0,
    VoidCallback? onCancel,
    Color? primaryColor,
    double pickerHeight = 300,
    double headerHeight = 50,
    double itemHeight = 40,
  }) {
    return showModalBottomSheet<T>(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true, // 允许内容自适应高度
      builder: (BuildContext context) {
        return CustomBottomPicker(
          title: title,
          options: options,
          displayKey: displayKey,
          initialIndex: initialIndex,
          onConfirm: onConfirm,
          onCancel: onCancel,
          primaryColor: primaryColor ?? AppColors.of(context).primaryColor,
          pickerHeight: pickerHeight,
          headerHeight: headerHeight,
          itemHeight: itemHeight,
        );
      },
    );
  }

  @override
  State<CustomBottomPicker> createState() => _CustomBottomPickerState<T>();
}

class _CustomBottomPickerState<T> extends State<CustomBottomPicker<T>> {
  late FixedExtentScrollController _scrollController;
  late int _selectedIndex;

  @override
  void initState() {
    super.initState();
    _selectedIndex = widget.initialIndex;
    _scrollController = FixedExtentScrollController(initialItem: widget.initialIndex);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  /// 获取选项的显示文本
  String _getDisplayText(T item) {
    if (item is String) {
      return item;
    } else if (item is Map<String, dynamic> && widget.displayKey != null) {
      return item[widget.displayKey]?.toString() ?? '';
    }
    return item.toString();
  }

  @override
  Widget build(BuildContext context) {
    final primaryColor = widget.primaryColor ?? Theme.of(context).primaryColor;

    return Container(
      height: widget.pickerHeight,
      decoration: BoxDecoration(
        color: AppColors.of(context).whiteColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        children: [
          // 头部
          _buildHeader(primaryColor),

          // 分割线
          const Divider(
            height: 0.5,
            thickness: 0.5,
            color: ColorUtils.lineColor,
          ),

          // 选择器内容
          Expanded(child: _buildPickerBody(primaryColor)),
        ],
      ),
    );
  }

  // 构建头部
  Widget _buildHeader(Color primaryColor) {
    return SizedBox(
      height: widget.headerHeight,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 取消按钮
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              if (widget.onCancel != null) {
                widget.onCancel!();
              }
            },
            child: const Text('取消', style: TextStyle(fontSize: 16, color: ColorUtils.textColors6)),
          ),

          // 标题
          Text(
            widget.title,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),

          // 确认按钮
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              widget.onConfirm(_selectedIndex, widget.options[_selectedIndex]);
            },
            child: Text(
              '完成',
              style: TextStyle(
                color: primaryColor,
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建选择器内容
  Widget _buildPickerBody(Color primaryColor) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: NotificationListener<ScrollNotification>(
        onNotification: (scrollNotification) {
          if (scrollNotification is ScrollEndNotification) {
            setState(() {
              _selectedIndex = _scrollController.selectedItem;
            });
          }
          return true;
        },
        child: ListWheelScrollView.useDelegate(
          controller: _scrollController,
          itemExtent: widget.itemHeight,
          physics: const FixedExtentScrollPhysics(),
          perspective: 0.005,
          diameterRatio: 1.5,
          childDelegate: ListWheelChildBuilderDelegate(
            childCount: widget.options.length,
            builder: (context, index) {
              final isSelected = index == _selectedIndex;
              final item = widget.options[index];
              final displayText = _getDisplayText(item);

              return Center(
                child: Text(
                  displayText,
                  style: TextStyle(
                    color: isSelected ? primaryColor : Colors.grey,
                    fontSize: isSelected ? 18 : 16,
                    fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              );
            },
          ),
          onSelectedItemChanged: (int index) {
            setState(() {
              _selectedIndex = index;
            });
          },
        ),
      ),
    );
  }
}
